package com.dkd.manage.task.allocator.service;

import com.dkd.manage.domain.Emp;
import com.dkd.manage.domain.VendingMachine;
import com.dkd.manage.task.allocator.model.EmployeePerformance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

@Slf4j
@Service
public class PerformanceCalculator {

    private final com.dkd.manage.service.ITaskService taskService;
    private final com.dkd.manage.service.IEmpService empService;

    // 使用构造器注入替代字段注入
    @Autowired
    public PerformanceCalculator(com.dkd.manage.service.ITaskService taskService,
                                 com.dkd.manage.service.IEmpService empService) {
        this.taskService = taskService;
        this.empService = empService;
    }

    public EmployeePerformance calculateEmployeePerformance(Long empId) {
        log.debug("计算员工绩效，员工ID: {}", empId);

        try {
            // 获取员工基本信息
            Emp emp = empService.selectEmpById(empId);
            if (emp == null) {
                log.warn("未找到员工信息: {}", empId);
                return createDefaultPerformance(empId);
            }

            // 获取绩效统计数据
            Integer completedTasks = taskService.countCompletedTasksByEmp(empId);
            Integer totalTasks = taskService.countTotalTasksByEmp(empId);
            Integer currentWorkload = taskService.countCurrentTasksByEmp(empId);
            Integer successfulTasks = taskService.countSuccessfulTasksByEmp(empId);
            Integer todayTasks = taskService.countTodayTasksByEmp(empId);
            Double avgCompletionTime = taskService.getAvgCompletionTimeByEmp(empId);
            Double avgQualityScore = taskService.getAvgQualityScoreByEmp(empId);
            Double completionRate = taskService.getTaskCompletionRate(empId);
            Double successRate = totalTasks > 0 ? (double) successfulTasks / totalTasks : 0.85;

            // 计算综合绩效分
            Double performanceScore = calculateComprehensivePerformanceScore(
                    completedTasks, totalTasks, avgCompletionTime, successRate,
                    currentWorkload, avgQualityScore, completionRate);

            // 获取熟悉的设备类型
            Set<String> skilledMachines = taskService.getSkilledMachinesByEmp(empId);

            // 使用setter方法创建绩效对象，而不是构造函数
            EmployeePerformance performance = new EmployeePerformance();
            performance.setEmpId(empId);
            performance.setCompletedTasks(completedTasks != null ? completedTasks : 0);
            performance.setTotalTasks(totalTasks != null ? totalTasks : 0);
            performance.setAvgCompletionTime(avgCompletionTime != null ? avgCompletionTime : 4.0);
            performance.setSuccessRate(successRate);
            performance.setCurrentWorkload(currentWorkload != null ? currentWorkload : 0);
            performance.setTodayTasks(todayTasks != null ? todayTasks : 0);
            performance.setAvgQualityScore(avgQualityScore != null ? avgQualityScore : 5.0);
            performance.setCompletionRate(completionRate != null ? completionRate : 0.8);
            performance.setSkilledMachines(skilledMachines);
            performance.setPerformanceScore(performanceScore);
            performance.setLastUpdateTime(new Date());

            // 设置员工技能等级
            performance.setSkillLevel(emp.getSkillLevel());

            return performance;

        } catch (Exception e) {
            log.error("计算员工绩效异常: {}", e.getMessage(), e);
            return createDefaultPerformance(empId);
        }
    }

    private EmployeePerformance createDefaultPerformance(Long empId) {
        EmployeePerformance performance = new EmployeePerformance();
        performance.setEmpId(empId);
        performance.setSkillLevel(1); // 默认技能等级
        performance.setLastUpdateTime(new Date());
        return performance;
    }

    // 保留这个更完整的 calculateSkillMatch 方法，删除下面的简单版本
    public double calculateSkillMatch(Long empId, VendingMachine machine) {
        try {
            Emp emp = empService.selectEmpById(empId);
            if (emp == null) {
                return 0.5; // 默认匹配度
            }

            Set<String> skilledMachines = taskService.getSkilledMachinesByEmp(empId);

            // 检查是否擅长该设备类型
            if (skilledMachines.contains(String.valueOf(machine.getVmTypeId()))) {
                return 1.0; // 完全匹配
            }

            // 如果员工有专长领域，检查是否包含该设备类型
            if (emp.getSpecialization() != null &&
                    emp.getSpecialization().contains(String.valueOf(machine.getVmTypeId()))) {
                return 0.8; // 专长匹配
            }

            // 基于技能等级的通用匹配度
            Integer skillLevel = emp.getSkillLevel();
            if (skillLevel == null) skillLevel = 1;

            // 技能等级越高，适应新设备的能力越强
            return 0.3 + (skillLevel * 0.1); // 1级: 0.4, 5级: 0.8

        } catch (Exception e) {
            log.error("计算技能匹配度异常: {}", e.getMessage());
            return 0.5;
        }
    }

    private Double calculateComprehensivePerformanceScore(Integer completedTasks, Integer totalTasks,
                                                          Double avgCompletionTime, Double successRate,
                                                          Integer currentWorkload, Double avgQualityScore,
                                                          Double completionRate) {
        double score = 0.0;

        // 1. 工作效率 (25%)
        score += calculateEfficiencyScore(avgCompletionTime) * 0.25;

        // 2. 工作质量 (20%)
        score += calculateQualityScore(avgQualityScore) * 0.20;

        // 3. 任务成功率 (15%)
        score += successRate * 15;

        // 4. 负载状况 (15%)
        score += calculateWorkloadScore(currentWorkload) * 0.15;

        // 5. 完成率 (10%)
        score += calculateCompletionRateScore(completionRate) * 0.10;

        // 6. 经验水平 (10%)
        score += calculateExperienceScore(completedTasks) * 0.10;

        // 7. 稳定性 (5%)
        score += calculateStabilityScore(completedTasks, totalTasks) * 0.05;

        return Math.min(score, 10.0);
    }

    private double calculateEfficiencyScore(Double avgCompletionTime) {
        if (avgCompletionTime == null) return 6.0;
        if (avgCompletionTime <= 2.0) return 10.0;
        if (avgCompletionTime <= 3.0) return 9.0;
        if (avgCompletionTime <= 4.0) return 7.0;
        if (avgCompletionTime <= 5.0) return 5.0;
        if (avgCompletionTime <= 6.0) return 3.0;
        return 1.0;
    }

    private double calculateQualityScore(Double avgQualityScore) {
        if (avgQualityScore == null) return 6.0;
        if (avgQualityScore >= 9.0) return 10.0;
        if (avgQualityScore >= 8.0) return 9.0;
        if (avgQualityScore >= 7.0) return 7.0;
        if (avgQualityScore >= 6.0) return 5.0;
        if (avgQualityScore >= 5.0) return 3.0;
        return 1.0;
    }

    private double calculateWorkloadScore(Integer currentWorkload) {
        if (currentWorkload == null || currentWorkload == 0) return 10.0;
        if (currentWorkload <= 2) return 9.0;
        if (currentWorkload <= 4) return 7.0;
        if (currentWorkload <= 6) return 5.0;
        if (currentWorkload <= 8) return 3.0;
        return 1.0;
    }

    private double calculateCompletionRateScore(Double completionRate) {
        if (completionRate == null) return 6.0;
        return completionRate * 10;
    }

    private double calculateExperienceScore(Integer completedTasks) {
        if (completedTasks == null || completedTasks == 0) return 3.0;
        if (completedTasks >= 50) return 10.0;
        if (completedTasks >= 30) return 8.5;
        if (completedTasks >= 20) return 7.0;
        if (completedTasks >= 10) return 5.5;
        if (completedTasks >= 5) return 4.0;
        return 3.0;
    }

    private double calculateStabilityScore(Integer completedTasks, Integer totalTasks) {
        if (totalTasks == null || totalTasks < 5) return 6.0;
        double stability = (double) completedTasks / totalTasks;
        if (stability >= 0.9) return 10.0;
        if (stability >= 0.8) return 8.0;
        if (stability >= 0.7) return 6.0;
        if (stability >= 0.6) return 4.0;
        return 2.0;
    }

    // 删除重复的 calculateSkillMatch 方法，只保留上面的完整版本
}